import Vue from 'vue'
import axios from 'axios'
// import qs from 'qs';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

function getXUserToken() {
    // XUserToken在wyt-entry-toB项目中存在
    if (localStorage.XUserToken) {
        return localStorage.XUserToken
    }
    return ''
}
// 创建axios实例
const instance = axios.create({
    baseURL: '/',
    headers: {
        'X-Access-Source': 'roc'
    }
})
// 拦截请求头
instance.interceptors.request.use(
    (config) => {
        config.headers['X-Access-Token'] = sessionStorage.accessToken || ''
        let userToken = getXUserToken()
        config.headers['X-User-Token'] = userToken || ''
        return config
    },
    (error) => {
        return Promise.reject(error.response)
    }
)
// 拦截响应头
instance.interceptors.response.use(
    (response) => {
        if (response.data.code === '0') {
            return response
        } else {
            return Promise.reject(response)
        }
    },
    (error) => {
        return Promise.reject(error.response)
    }
)
// 请求回调处理函数
const sucFun = (res) => {
    NProgress.done()
    return res.data
}
const errFun = (err) => {
    NProgress.done()
    // Vue.prototype.$message({
    //     type: 'error',
    //     message: err.data.message || err.statusText || '数据异常'
    // });
    console.log(err.data.message || err.statusText || '数据异常')
    // Vue.toast && Vue.toast(err.data.message || err.statusText || "数据异常");
    return err.data
}
// 普通POST请求
export const Posting = (url = '', data = {}) => {
    NProgress.start()
    return instance.post(url, data).then(sucFun).catch(errFun)
}
// 普通Get请求
export const Geting = (url = '', data = {}) => {
    NProgress.start()
    let reqData = {
        params: data
    }
    return instance.get(url, reqData).then(sucFun).catch(errFun)
}
// 文件流请求
const PostingBlob = (url = '', data = {}) => {
    NProgress.start()
    let config = {
        method: 'post',
        url,
        data,
        headers: {
            'X-Access-Source': 'roc'
        },
        responseType: 'blob'
    }
    return axios(config).then(sucFun).catch(errFun)
}
//  默认请求
Vue.prototype.$axios = axios
Vue.axios = axios
// 普通POST请求
Vue.prototype.$Posting = Posting
Vue.Posting = Posting
// 普通Get请求
Vue.prototype.$Geting = Geting
Vue.Geting = Geting
// 文件流请求
Vue.prototype.$PostingBlob = PostingBlob
Vue.PostingBlob = PostingBlob
